import json
import random
from shapely.geometry import Polygon, Point, LineString
import numpy as np


def generate_interior_point(polygon_coords, attempts=1000):
    """
    生成多边形内部且远离边界的随机点
    参数：
        polygon_coords : 多边形顶点坐标列表 [(lng, lat), ...]
        attempts       : 最大尝试次数
    返回：
        (最佳点坐标, 到边界最近距离) 或 None
    """
    # 创建多边形对象
    polygon = Polygon(polygon_coords)

    # 获取多边形外环的所有边
    exterior = list(polygon.exterior.coords)
    edges = [
        LineString([exterior[i], exterior[i + 1]])
        for i in range(len(exterior) - 1)
    ]

    # 获取多边形包围盒
    min_lng, min_lat, max_lng, max_lat = polygon.bounds

    best_point = None
    max_min_dist = 0

    for _ in range(attempts):
        # 生成随机点
        lng = random.uniform(min_lng, max_lng)
        lat = random.uniform(min_lat, max_lat)
        point = Point(lng, lat)

        if polygon.contains(point):
            print(f"[{point.x}, {point.y}]")
            # 计算到所有边的最短距离
            min_dist = min(edge.distance(point) for edge in edges)

            if min_dist > max_min_dist:
                max_min_dist = min_dist
                best_point = (lng, lat)

                # 提前退出条件（可选）
                if max_min_dist > np.sqrt((max_lng - min_lng) ** 2 + (max_lat - min_lat) ** 2) / 4:
                    break

    if best_point:
        return best_point, max_min_dist
    return None

def generate_sign_data_by_userconfig(positions: list[dict]) -> str:
    res = []
    for position in positions:
        if not position["enable"]:
            continue
        res.append({
            "Reason": "",
            "AttachmentFileName": "",
            "LngLat": ",".join([
            str(position["LngLat"][0] + round(random.uniform(-position["offsetRange"][0], position["offsetRange"][0]), 13)),
            str(position["LngLat"][1] + round(random.uniform(-position["offsetRange"][1], position["offsetRange"][1]), 13)),
        ]),
            "Address": position["Address"],
        })
    if len(res) == 0:
        raise ValueError("用户配置错误")
    index = random.randint(0, len(res) - 1)
    return json.dumps(res[index], ensure_ascii=False)

# 示例用法
if __name__ == "__main__":
    # 示例多边形坐标（闭合多边形）
    from userData import users
    for i in users:
        print(generate_sign_data_by_userconfig(i["signChoices"]))